const { readFile, writeFile, stat, readdir } = require('fs');
const XLSX = require('xlsx');
const { join, extname, dirname } = require('path');

async function walk(filePath) {
    const xlsxPaths = [];
    if (Array.isArray(filePath)) {
        for (const subPath of filePath)
            xlsxPaths.push(await walk(subPath));
        return xlsxPaths.flat();
    }

    const fileStat = await new Promise((r) => { stat(filePath, (err, state) => { r(state) }) });
    if (!fileStat.isDirectory()) {
        const ext = extname(filePath);
        if (filePath.indexOf("~") < 0 && (ext == '.xls' || ext == '.xlsx')) xlsxPaths.push(filePath);
        return xlsxPaths;
    }

    const dirData = await new Promise((r) => { readdir(filePath, (err, files) => { r(files) }) });
    for (const subPath of dirData)
        xlsxPaths.push(await walk(join(filePath, subPath)));
    let arr = [];
    xlsxPaths.forEach((v) => {
        arr.push(v[0]);
    })
    return arr.filter(v => !!v);
}

let isEmptyObject = function (obj) {
    for (const key in obj) {
        return false;
    }
    return true;
}

async function main() {
    const filePaths = join(__dirname, "../", 'excel');
    if (filePaths.length < 0) process.exit(0);
    const xlsxs = await walk(filePaths);
    const sPath = join(__dirname, "../", "assets", "bundle", "config");
    console.error(xlsxs);
    for (const p of xlsxs) {
        let workbook = XLSX.readFile(p);
        let sheets = workbook.Sheets;
        for (const sheetName in sheets) {
            const sheetRawData = sheets[sheetName];
            if (!sheetRawData['!ref']) break;
            // console.error("sheetRawData",JSON.stringify(sheetRawData))
            let json = XLSX.utils.sheet_to_json(sheetRawData);
            let newData = [];
            let data = {}
            for (const iterator of json) {
                for (const key in iterator) {
                    data[key] = iterator[key];
                }
            }
            if (!isEmptyObject(data)) newData.push(data);
            // console.error(JSON.stringify(newData));
            let savePath = join(sPath, `${sheetName}.json`);
            await new Promise(r => {
                writeFile(
                    savePath,
                    JSON.stringify(newData, null, 4),
                    () => {
                        r();
                    }
                );
            })
        }
    }
}

main();